<template>
  <div class="page art-full-height">
    <ArtSearchBar
      ref="searchBarRef"
      v-model="searchParams"
      :items="formItems"
      @reset="resetSearchParams"
      @search="getData"
    >
    </ArtSearchBar>
    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton @click="showDialog('add')" v-ripple>新增</ElButton>
            <ElButton type="warning" plain @click="showDialog('add')" v-ripple>导出</ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>
    </ElCard>
    <ElDrawer
      v-model="dialogVisible"
      :title="dialogType === 'edit' ? '添加角色信息表' : '编辑角色信息表'"
      width="300px"
      align-center
    >
      <ElForm ref="formRef" :model="form" :rules="rules" label-width="80px">
         <ElFormItem label="角色ID" prop="roleId">
           <ElInput v-model="form.roleId" />
         </ElFormItem>
         <ElFormItem label="租户编号" prop="tenantId">
           <ElInput v-model="form.tenantId" />
         </ElFormItem>
         <ElFormItem label="角色名称" prop="roleName">
           <ElInput v-model="form.roleName" />
         </ElFormItem>
         <ElFormItem label="角色权限字符串" prop="roleKey">
           <ElInput v-model="form.roleKey" />
         </ElFormItem>
         <ElFormItem label="显示顺序" prop="roleSort">
           <ElInput v-model="form.roleSort" />
         </ElFormItem>
         <ElFormItem label="数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限 5：仅本人数据权限 6：部门及以下或本人数据权限）" prop="dataScope">
           <ElInput v-model="form.dataScope" />
         </ElFormItem>
         <ElFormItem label="菜单树选择项是否关联显示" prop="menuCheckStrictly">
           <ElInput v-model="form.menuCheckStrictly" />
         </ElFormItem>
         <ElFormItem label="部门树选择项是否关联显示" prop="deptCheckStrictly">
           <ElInput v-model="form.deptCheckStrictly" />
         </ElFormItem>
         <ElFormItem label="角色状态（0正常 1停用）" prop="status">
           <ElInput v-model="form.status" />
         </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="dialogVisible = false">取消</ElButton>
          <ElButton type="primary" @click="handleSubmit">提交</ElButton>
        </div>
      </template>
    </ElDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
  import { useTable } from '@/hooks/useTable'
  import { SysRoleService, SysRoleVO, SysRoleForm } from '@/service/SysRoleService'
  import ArtButtonTable from '@/components/forms/art-button-table/index.vue'

  const initForm: SysRoleForm = {
    roleId: '',
    tenantId: '',
    roleName: '',
    roleKey: '',
    roleSort: '',
    dataScope: '',
    menuCheckStrictly: '',
    deptCheckStrictly: '',
    status: '',
    id: ''
  }

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: SysRoleService.list,
      apiParams: {
        current: 1,
        size: 20,
        ...initForm
      },
      columnsFactory: () => [
        {
          prop: 'roleId',
          label: '角色ID'
        },
        {
          prop: 'tenantId',
          label: '租户编号'
        },
        {
          prop: 'roleName',
          label: '角色名称'
        },
        {
          prop: 'roleKey',
          label: '角色权限字符串'
        },
        {
          prop: 'roleSort',
          label: '显示顺序'
        },
        {
          prop: 'dataScope',
          label: '数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限 5：仅本人数据权限 6：部门及以下或本人数据权限）'
        },
        {
          prop: 'menuCheckStrictly',
          label: '菜单树选择项是否关联显示'
        },
        {
          prop: 'deptCheckStrictly',
          label: '部门树选择项是否关联显示'
        },
        {
          prop: 'status',
          label: '角色状态（0正常 1停用）'
        },
        {
          prop: 'remark',
          label: '描述'
        },
        {
          prop: 'createTime',
          label: '创建日期',
          sortable: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 240,
          fixed: 'right',
          formatter: (row: SysRoleVO) => {
            if (row.id != 1) {
              return h('div', [
                h(ArtButtonTable, {
                  type: 'edit',
                  onClick: () => showDialog('edit', row)
                }),
                h(ArtButtonTable, {
                  type: 'delete',
                  onClick: () => deleteRole(row)
                })
              ])
            }
            // 明确返回 null 或空内容，避免无返回值的情况
            return null
          }
        }
      ]
    }
  })

  const dialogType = ref<'add' | 'edit'>('add')

  const showDialog = async (type: 'add' | 'edit', row?: SysRoleVO) => {
    const id = row?.id || ids.value[0]
    const { data } = await SysRoleService.get(id)
    Object.assign(form, data)
    dialogVisible.value = true
    dialogType.value = type
    if (dialogType.value === 'edit' && row) {
      Object.assign(form, { ...row })
    } else {
      Object.assign(form, { ...initForm })
    }
  }

  const deleteRole = (row: SysRoleVO) => {
    ElMessageBox.confirm(`确定删除吗？此操作不可恢复！`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        await SysRoleService.del(row.id)
        ElMessage.success('删除成功')
        await refreshData()
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }

  // 表单配置
  const formItems = computed(() => [
    {
      label: '角色ID',
      key: 'roleId',
      type: 'input',
      placeholder: '请输入角色ID',
      clearable: true
    },
    {
      label: '租户编号',
      key: 'tenantId',
      type: 'input',
      placeholder: '请输入租户编号',
      clearable: true
    },
    {
      label: '角色名称',
      key: 'roleName',
      type: 'input',
      placeholder: '请输入角色名称',
      clearable: true
    },
    {
      label: '角色权限字符串',
      key: 'roleKey',
      type: 'input',
      placeholder: '请输入角色权限字符串',
      clearable: true
    },
    {
      label: '显示顺序',
      key: 'roleSort',
      type: 'input',
      placeholder: '请输入显示顺序',
      clearable: true
    },
    {
      label: '数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限 5：仅本人数据权限 6：部门及以下或本人数据权限）',
      key: 'dataScope',
      type: 'input',
      placeholder: '请输入数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限 5：仅本人数据权限 6：部门及以下或本人数据权限）',
      clearable: true
    },
    {
      label: '菜单树选择项是否关联显示',
      key: 'menuCheckStrictly',
      type: 'input',
      placeholder: '请输入菜单树选择项是否关联显示',
      clearable: true
    },
    {
      label: '部门树选择项是否关联显示',
      key: 'deptCheckStrictly',
      type: 'input',
      placeholder: '请输入部门树选择项是否关联显示',
      clearable: true
    },
    {
      label: '角色状态（0正常 1停用）',
      key: 'status',
      type: 'input',
      placeholder: '请输入角色状态（0正常 1停用）',
      clearable: true
    },
    {
      label: '备注',
      key: 'remark',
      type: 'input',
      placeholder: '请输入备注',
      clearable: true
    },
    {
      label: '创建日期',
      key: 'createTime',
      type: 'datetime',
      props: {
        style: { width: '100%' },
        placeholder: '请选择日期范围',
        type: 'createTime',
        rangeSeparator: '至',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD',
        shortcuts: [
          { text: '今日', value: [new Date(), new Date()] },
          {
            text: '最近一周',
            value: [new Date(Date.now() - 604800000), new Date()]
          },
          {
            text: '最近一个月',
            value: [new Date(Date.now() - 2592000000), new Date()]
          }
        ]
      }
    }
  ])

  const ids = ref<Array<string | number>>([])

  const dialogVisible = ref(false)
  const formRef = ref<FormInstance>()
  let form = reactive<SysRoleForm>({ ...initForm })
  const rules = reactive<FormRules>({})
  const handleClose = () => {
    dialogVisible.value = false
    formRef.value?.resetFields()
  }
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          if (form.id) {
            await SysRoleService.update(form)
          } else {
            await SysRoleService.add(form)
          }
          ElMessage.success(`操作成功`)
          await refreshData()
          handleClose()
        } catch {
          ElMessage.error(`操作失败`)
        }
      }
    })
  }
</script>

<style lang="scss" scoped>
  .page {
    padding-bottom: 15px;
  }
</style>
